/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-09-02 15:37:16
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-09-02 16:12:29
 * @FilePath: /code/lesson33/testCond/testCond.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
using namespace std;
#include <pthread.h>
#include <vector>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* MasterRun(void* arg)
{
    while(true)
    {
        sleep(1);
        pthread_cond_signal(&cond);
        cout << "唤醒一个线程..." << endl;
    }
}

void* SlaverRun(void* arg)
{
    string name = static_cast<char*>(arg);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);

        cout << name << "被唤醒..." << endl;

        pthread_mutex_unlock(&mutex);
    }
}

void StartMaster(vector<pthread_t>* tids)
{
    sleep(3);
    pthread_t tid;
    cout << "Master线程开始工作..." << endl;
    int n = pthread_create(&tid, nullptr, MasterRun, nullptr);
    if(n == 0)
    {
        cout << "创建主线程success..." << endl;
    }
    tids->emplace_back(tid);
}

void StartSlaver(vector<pthread_t>* tids, int num)
{
    pthread_t tid;
    for(int i = 0; i < num; i++)
    {
        char* name = new char[64]{0};
        snprintf(name, 64 * sizeof(char), "pthread-%d", i + 1);
        int n = pthread_create(&tid, nullptr, SlaverRun, (void*)name);
        if(n == 0)
        {
            cout << "创建任务线程success..." << endl;
        }
        tids->emplace_back(tid);
    }
}

void JoinThread(vector<pthread_t>& tids)
{
    for(auto& tid : tids)
    {
        pthread_join(tid, nullptr);
    }
}

int main()
{
    //管理多个线程
    vector<pthread_t> tids;
    StartMaster(&tids);//创建主线程
    StartSlaver(&tids, 3);//创建其他线程
    JoinThread(tids);//回收所有线程

    return 0;
}